const deepObj = (obj) => JSON.parse(JSON.stringify(obj))
const S = () => (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1)
const guid = () => `${S()}${S()}-${S()}-${S()}-${S()}-${S()}${S()}${S()}`
function valiConfig(data) {
  return data?.value && Array.isArray(data.configList) && data.configList.length
}

/**获取配置 */
async function getConfig(url) {
  const response = await fetch(url)
  if (!response.ok) return []
  return await response.json()
}
/**更新配置 */
async function updateConfig(list) {
  const response = await fetch('/p-api/saveProxy', {
    method: 'post',
    body: JSON.stringify(list),
    headers: {
      'Content-Type': 'application/json'
    }
  })
  if (!response.ok) return
  const res = await response.json()
  if (res.code == 0) {
    vm.$message.success('保存成功')
  } else {
    vm.$message.error('保存失败')
  }
}

const vm = new Vue({
  el: '#app',
  data() {
    return {
      editId: '',
      activeConfig: '',
      configList: [],
      dialogVisible: false,
      proxyList: [],
      tableData: [],
      currentProxy: {
        id: '',
        title: '',
        head: '',
        value: '',
        requestLog: 0,
        list: []
      }
    }
  },
  created() {
    this.getProxyList()
  },
  methods: {
    /**获取代理列表 */
    async getProxyList() {
      const res = await getConfig('/proxyConfig.json')
      if (!valiConfig(res)) return
      this.configList = res.configList
      this.activeConfig = res.value
      this.handleConfigClick()
    },
    /**新增代理 */
    addProxy() {
      this.openType = 'create'
      this.tableData = []
      this.dialogVisible = true
      Object.assign(this.currentProxy, {
        id: guid(),
        title: '',
        head: '',
        value: '',
        requestLog: 0,
        list: []
      })
    },
    /**编辑代理 */
    editProxy(id) {
      this.openType = 'edit'
      this.editId = id
      this.dialogVisible = true
      const cur = this.getProxyById(id)
      Object.assign(this.currentProxy, deepObj(cur))
    },
    /**确认编辑 */
    comfirmProxy() {
      const { title, head, list } = this.currentProxy
      if (!title) return this.$message.error('名称不能为空')
      if (!head) return this.$message.error('代理头不能为空')
      if (!list.length) return this.$message.error('url不能为空')
      if (this.openType == 'create') {
        this.currentProxy.value = this.currentProxy.list[0].url
        this.proxyList.push(deepObj(this.currentProxy))
      } else {
        const cur = this.getProxyById(this.editId)
        Object.assign(cur, deepObj(this.currentProxy))
      }
      this.dialogVisible = false
    },
    /**删除代理 */
    async removeProxy(id) {
      const cur = this.getProxyById(id)
      if (!cur) return
      await this.$confirm(`确定删除代理 ${cur.title} 吗？`)
      this.proxyList = this.proxyList.filter((e) => e.id != id)
    },
    /**新增url */
    addUrl() {
      this.currentProxy.list.push({ name: '', url: '' })
    },
    /**删除地址 */
    async removeUrl(url) {
      await this.$confirm(`确定删除地址 ${url} 吗？`)
      const urlList = this.currentProxy.list
      this.currentProxy.list = urlList.filter((e) => e.url != url)
    },
    /**根据id获取代理 */
    getProxyById(id) {
      return this.proxyList.find((e) => e.id == id)
    },
    /**保存代理配置 */
    async onSaveProxy() {
      await this.$confirm('确定保存吗？')
      await updateConfig({
        configList: this.configList,
        value: this.activeConfig
      })
    },
    /**导入 */
    async onImport(file) {
      const url = URL.createObjectURL(file.raw)
      const res = await getConfig(url)
      if (valiConfig(res)) {
        await this.$confirm('导入将覆盖本地配置确认导入吗?')
        await updateConfig(res)
        setTimeout(() => {
          this.getProxyList()
        }, 800)
      } else {
        this.$message.error('数据格式不正确无法导入')
      }
    },
    /**配置选择 */
    handleConfigClick() {
      const cur = this.configList.find((e) => e.value == this.activeConfig)
      this.proxyList = cur.proxyList
    },
    /**新增配置 */
    async addConfig() {
      const res = await this.$prompt('配置标题', '提示', {
        closeOnClickModal: false,
        inputValidator: (v) => !!v,
        inputErrorMessage: '请填写配置标题'
      })
      if (!res.value) {
        console.log('标题不能为空')
        return
      }
      let newTabName = this.configList.length + 1 + ''
      this.configList.push({
        name: res.value,
        value: newTabName,
        proxyList: []
      })
      this.activeConfig = newTabName
      this.handleConfigClick()
    },
    /**删除配置 */
    async removeTab(targetName) {
      await this.$confirm('确定删除吗？')
      this.configList = this.configList.filter((e) => e.value != targetName)
      if (this.activeConfig == targetName) {
        this.activeConfig = this.configList[0]?.value || ''
      }
    }
  }
})
